package fule.com.playandroidkotlin.ui.activity

import android.app.ActivityOptions
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import butterknife.OnClick
import fule.com.playandroidkotlin.R
import fule.com.playandroidkotlin.base.BaseActivity
import fule.com.playandroidkotlin.ui.adapter.HotSearchAdapter
import fule.com.playandroidkotlin.ui.adapter.SearchHistoryAdapter
import fule.com.playandroidkotlin.ui.impl.HistoryImpl
import fule.com.playandroidkotlin.ui.model.HotKeyModel
import fule.com.playandroidkotlin.ui.model.SearchModel
import fule.com.playandroidkotlin.ui.presenter.SearchPresenter
import fule.com.playandroidkotlin.ui.util.AppConstant
import fule.com.playandroidkotlin.ui.util.RegexUtils
import fule.com.playandroidkotlin.ui.util.SoftInputUtils
import fule.com.playandroidkotlin.ui.util.ToastUtils
import fule.com.playandroidkotlin.ui.view.SearcherView
import fule.com.playandroidkotlin.ui.weight.DividerDecoration
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.toolbar_search.*

/**
 * 作者： njb
 * 时间： 2018/8/11 0011-下午 4:57
 * 描述： 搜索
 * 来源：
 */
class SearchActivity : BaseActivity<SearchPresenter>(), (SearcherView) {
    private var hotSearchAdapter: HotSearchAdapter? = null
    private var historyAdapter: SearchHistoryAdapter? = null
    private var linearLayoutManager: LinearLayoutManager? = null
    private var historyList: MutableList<String>? = null

    override val layoutId: Int
        get() = R.layout.activity_search

    override fun createPresenter(): SearchPresenter {
        return SearchPresenter(this)
    }

    override fun initView() {
        toolbar.run {
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        toolbar_title!!.text = "搜索"
        initAdapter()
        initHistoryAdapter()
        presenter!!.hotkey()
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        toolbar.title = ""
        toolbar.subtitle = ""
    }

    private fun initAdapter() {
        hotSearchAdapter = HotSearchAdapter(null)
        hotSearchAdapter.run {
            var manager = GridLayoutManager(context, 3)
            rv_hot.layoutManager = manager
        }
        rv_hot.run {
            rv_hot.addItemDecoration(DividerDecoration(ContextCompat.getColor(context, R.color.ce7e7e7), 1))
            rv_hot.adapter = hotSearchAdapter
        }
    }

    private fun initHistoryAdapter() {
        historyAdapter = SearchHistoryAdapter(null)
        linearLayoutManager = LinearLayoutManager(this)
        rv_history.layoutManager = linearLayoutManager
        rv_history.adapter = historyAdapter
        historyAdapter!!.setOnItemClickListener { _, _, _ ->
            startActivity(intent)
        }
    }

    override fun addListener() {
        et_search.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (TextUtils.isEmpty(et_search.text.toString())) {
                    ToastUtils.ToastShort("请输入关键字")
                    return@OnEditorActionListener false
                }
                if (!RegexUtils.stringFilter(et_search.text.toString())) {
                    ToastUtils.ToastShort(this, "您输入的内容不合法")
                    return@OnEditorActionListener false
                }
                // 当按了搜索之后关闭软键盘
                SoftInputUtils.hideSoftInput(this)
                HistoryImpl.addHistory(et_search.text.toString())
                Intent(context, SearchResultActivity::class.java).run {
                    putExtra(AppConstant.ARTICLELIST_TITLE, et_search.text.toString())
                    startActivity(this, null)
                }
                return@OnEditorActionListener true
            }
            false
        })
        et_search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
            ) {
            }

            override fun onTextChanged(
                    s: CharSequence,
                    start: Int,
                    before: Int,
                    count: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (s.isNotEmpty()) {
                    iv_delete.visibility = View.VISIBLE
                } else {
                    iv_delete.visibility = View.GONE
                }
            }
        })

        hotSearchAdapter!!.setOnItemClickListener { _, view, position ->
            val options: ActivityOptions = ActivityOptions.makeScaleUpAnimation(view,
                    view.width / 2,
                    view.height / 2,
                    0,
                    0)
            Intent(context, SearchResultActivity::class.java).run {
                putExtra(AppConstant.ARTICLELIST_TITLE, hotSearchAdapter!!.getItem(position)!!.name)
                HistoryImpl.addHistory(hotSearchAdapter!!.getItem(position)!!.name)
                startActivity(this, options.toBundle())
            }
        }
        historyAdapter!!.setOnItemClickListener { _, view, position ->
            val options: ActivityOptions = ActivityOptions.makeScaleUpAnimation(view,
                    view.width / 2,
                    view.height / 2,
                    0,
                    0)
            Intent(context, SearchResultActivity::class.java).run {
                putExtra(AppConstant.ARTICLELIST_TITLE, historyAdapter!!.getItem(position)!!)
                startActivity(this, options.toBundle())
            }
        }
    }

    override fun onResume() {
        super.onResume()
        historyList = HistoryImpl.getHistoryList()
        historyAdapter!!.setNewData(historyList)
    }

    @OnClick(R.id.tv_search_cancel, R.id.iv_delete, R.id.search_history_clear_all_tv)
    fun onViewClicked(view: View) {
        when (view.id) {
            R.id.tv_search_cancel -> finish()
            R.id.iv_delete -> et_search.text.clear()
            R.id.search_history_clear_all_tv -> {
                HistoryImpl.clearHistory()
                if (historyList != null) {
                    historyList!!.clear()
                    historyAdapter!!.notifyDataSetChanged()
                    ToastUtils.ToastShort("清空成功")
                }
            }
        }
    }

    override fun onLoadSearcher(data: List<SearchModel>) {

    }

    override fun onLoadHot(data: List<HotKeyModel>) {
        hotSearchAdapter!!.setNewData(data)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {
    }
}